export const compressImage = async (
  file: File,
  maxSizeMB: number = 2,
  initialQuality: number = 0.7,
): Promise<string> => {
  const MAX_BASE64_SIZE = maxSizeMB * 1024 * 1024

  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)

    reader.onload = (e) => {
      const img = new Image()
      img.src = e.target?.result as string

      img.onload = async () => {
        const quality = initialQuality
        let base64String = ''
        let width = img.width
        let height = img.height

        // 首先尝试调整尺寸
        const MAX_DIMENSION = 1024
        if (width > MAX_DIMENSION || height > MAX_DIMENSION) {
          const ratio = Math.min(MAX_DIMENSION / width, MAX_DIMENSION / height)
          width = Math.floor(width * ratio)
          height = Math.floor(height * ratio)
        }

        const canvas = document.createElement('canvas')
        const ctx = canvas.getContext('2d')
        canvas.width = width
        canvas.height = height

        ctx?.drawImage(img, 0, 0, width, height)
        base64String = canvas.toDataURL('image/jpeg', quality)

        if (base64String.length > MAX_BASE64_SIZE) {
          reject(new Error('图片太大，请选择更小的图片'))
          return
        }

        resolve(base64String)
      }

      img.onerror = () => reject(new Error('图片加载失败'))
    }

    reader.onerror = () => reject(new Error('文件读取失败'))
  })
}

export const formatFileSize = (bytes: number): string => {
  if (bytes === 0) return '0 Bytes'
  const k = 1024
  const sizes = ['Bytes', 'KB', 'MB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

export const getBase64Size = (base64String: string): number => {
  // 去掉base64头部信息（如：data:image/jpeg;base64,）
  const padding = base64String.substring(base64String.indexOf(',') + 1).length % 4
  const size = (base64String.length - base64String.indexOf(',') - 1) * 0.75
  return padding ? size - padding : size
}
